
<!-- 是templete 不是  templete -->
<template>
  <div>
    <!-- <ParamsComponent ref="paramsComponentRef" v-if="true"/> -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- :to="{ path: '/homePage' }" -->
      <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- <div @click="testMethod">测试方法</div> -->

    <el-alert
      title="添加商品信息"
      type="info"
      center
      show-icon
      :closable="false"
    >
    </el-alert>

    <!-- active需要绑定一个数字 -->
    <el-steps
      :space="500"
      :active="activeIndex - 0"
      finish-status="success"
      align-center
    >
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <el-form
      :model="addGoodsForm"
      :rules="addGoodsFormRules"
      ref="addGoodsFormRef"
      label-width="100px"
      label-position="top"
    >
      <!-- <el-button type="primary" @click="testForm('addGoodsFormRef')">测试</el-button> -->
      <el-button type="primary" @click="consoleManyTabData">测试</el-button>

      <!-- value / v-model	绑定值，选中选项卡的 name -->
      <el-tabs
        v-model="activeIndex"
        tab-position="left"
        :before-leave="beforeLeave"
        @tab-click="tabClick"
      >
        <!-- 第1个标签页 -->
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>

          <el-form-item label="商品价格" prop="goods_price">
            <el-input
              v-model="addGoodsForm.goods_price"
              type="number"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品重量" prop="goods_weight">
            <el-input
              v-model="addGoodsForm.goods_weight"
              type="number"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品数量" prop="goods_number">
            <el-input
              v-model="addGoodsForm.goods_number"
              type="number"
            ></el-input>
          </el-form-item>

          <!-- @change="handleChange" -->
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="cateList"
              :props="{ expandTrigger: 'hover', ...cascaderProps }"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>

        <!-- 第2个标签页 动态参数-->
        <el-tab-pane label="商品参数" name="1">
          <!-- 这里循环的元素为有很多属性的对象 -->
          <el-form-item
            :label="item.attr_name"
            v-for="item in manyTabData"
            :key="item.attr_id"
          >
            <!-- 这里循环的元素为一个个字符串 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                :border="true"
                :label="cb"
                v-for="(cb, i) in item.attr_vals"
                :key="i"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 第3个标签页 商品属性-->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyTabData"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>

        <!-- 第4个标签页 商品图片 -->
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            :action="uploadURL"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerParam"
            :on-success = "uploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-tab-pane>

         <!-- 第5个标签页 商品介绍 -->
        <el-tab-pane label="商品介绍" name="4">
          <el-form-item label="商品介绍" prop="goods_introduce">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
          </el-form-item>
          
          <el-button type="primary" @click="addGood" style="margin: 15px 0px 0px 1px;">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>
    
<script>
import ParamsComponent from "./Params.vue";
import _ from 'lodash'

export default {
  components: {
    //ParamsComponent
  },
  data() {
    var goods_cat_validate = (rule, value, callback) => {
      console.log("length is " + value.length);
      if (value.length !== 3) {
        return callback(new Error("请选择商品分类"));
      }
      // alert('length is ' +  value.length)
      callback();
    };
    //数据区
    return {
      activeIndex: "0",
      addGoodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_introduce: [
          { required: true, message: "请输入商品介绍", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
          {
            validator: goods_cat_validate,
            message: "请选择商品分类",
            trigger: ["blur", "change"],
          },
        ],
        
      },

      selectKeys: [],
      cateList: [],
      // 级联选择器属性
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      manyTabData: [],
      onlyTabData: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerParam: {
        Authorization: window.sessionStorage.getItem('token')
      }
    };
  },

  //方法区
  methods: {
    async getCateList() {
      const { data: resData } = await this.$http.get("categories");
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      this.cateList = resData.data;
    },

    testMethod() {
      this.$refs.paramsComponentRef.handleChange();
    },
    // async init(){
    //   //this.cateList = this.$refs["paramsComponentRef"].cateList
    //   this.$refs.paramsComponentRef.cateList
    //   const { data: resData } = await this.$refs.paramsComponentRef.getCateListV2()
    //   console.log(this.$refs.paramsComponentRef.getCateListV2())

    // }
    handleChange() {
      const goods_cat_length = this.addGoodsForm.goods_cat.length;
      if (goods_cat_length !== 3) {
        this.addGoodsForm.goods_cat = [];
      }
    },
    beforeLeave(activeName, oldActiveName) {
      console.log("activeName is " + activeName);
      console.log("oldActiveName is " + oldActiveName);
      let flag = true;
      if (oldActiveName === "0") {
        this.$refs["addGoodsFormRef"].validateField(
          [
            "goods_name",
            "goods_price",
            "goods_weight",
            "goods_number",
            "goods_cat",
          ],
          (valid) => {
            if (valid) {
              flag = false;
            }
          }
        );
        if (flag === false) {
          this.$message.error("【基本信息】项请按要求填写正确与完整");
          return false;
        }
      }
      return true;
    },

    async tabClick() {
      if (this.activeIndex === "1") {
        const { data: resData } = await this.$http.get(
          `categories/${this.cated}/attributes`,
          { params: { sel: "many" } }
        );
        if (resData.meta.status !== 200) {
          return this.$message.error(resData.meta.msg);
        }
        resData.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        this.manyTabData = resData.data;
      }
      if (this.activeIndex === "2") {
        const { data: resData } = await this.$http.get(
          `categories/${this.cated}/attributes`,
          { params: { sel: "only" } }
        );
        if (resData.meta.status !== 200) {
          return this.$message.error(resData.meta.msg);
        }
        this.onlyTabData = resData.data;
        
      }
    },
    testForm(formName) {
      console.log("formName is " + formName);
      let flag = true;
      let name = "addGoodsFormRef";
      this.$refs["addGoodsFormRef"].validateField(
        [
          "goods_name",
          "goods_price",
          "goods_weight",
          "goods_number",
          "goods_cat",
        ],
        (valid) => {
          if (valid) {
            // 放在里面 会出现3个叠加的弹框提示
            // this.$message.error('基本信息请填写完整')
            // return false
            flag = false;
          }
        }
      );

      if (flag === false) {
        return this.$message.error(
          "【基本信息】项请按要求填写正确与完整1111222333"
        );
      }
    },
    consoleManyTabData() {
      // 验证checkbox 勾选项去掉后它的attr_vals数组是否会减少
      console.log(this.manyTabData);
    },
    handlePreview(){

    },
    handleRemove(file){
      console.log(file)
      const tempAddGoodsForm = this.addGoodsForm
      const index = tempAddGoodsForm.pics.findIndex(item=>{
        item.pic = file.response.data.tmp_path
      })
      tempAddGoodsForm.pics.splice(index,1)
      this.addGoodsForm = tempAddGoodsForm
      console.log(this.addGoodsForm )
    },
    uploadSuccess(response){
      console.log(response)
      if(response.meta.status === 200){
        this.$message.success("上传成功")
      }
      // 尽量避免用this.属性数据进行任何赋值以外的操作,以防出现额外的错误,
      // 分类参数排查好久才看出问题
      const picItem  = {pic: response.data.tmp_path}
      const tempAddGoodsForm = this.addGoodsForm
      tempAddGoodsForm.pics.push(picItem)
      this.addGoodsForm = tempAddGoodsForm
      console.log('addGoodsForm is ')
      console.log(this.addGoodsForm)
    },

    //添加商品
    async addGood(){
      let flag = true;
      this.$refs["addGoodsFormRef"].validateField(
        [
          "goods_introduce",
        ],
        (valid) => {
          if (valid) {
            flag = false;
          }
        }
      )
      if (flag === false) {
        return this.$message.error(
          "请添写商品介绍"
        );
      }
      
      // 深拷贝对象,避免级联选择器要求goods_cat是数组,而接口api要求是字符串之间的冲突
      const newGoodsForm =  _.cloneDeep(this.addGoodsForm)
      newGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
      this.manyTabData.forEach(item => {
         const newObj = {attr_id: item.attr_id,attr_value: item.attr_vals.join(',')}
         newGoodsForm.attrs.push(newObj)
      })
      this.onlyTabData.forEach(item => {
         const newObj = {attr_id: item.attr_id,attr_value: item.attr_vals}
         newGoodsForm.attrs.push(newObj)
      })

      const{data: resData} = await this.$http.post("goods",newGoodsForm)

      if(resData.meta.status !== 201) return this.$message.error(resData.meta.msg);
      this.$router.push('/goods')
      return this.$message.success("添加商品成功");
    }

  },

  computed: {
    cated() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },

  //钩子函数
  created() {
    this.getCateList();
    //this.$refs.paramsComponentRef.handleChange();
    // this.$nextTick(()=>{ this.init() })
  },
};
</script>
    
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>